﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace IWS.SiteManager.Core.Model
{
	public class SiteRepository
	{
		SiteManagerDataContext _DB;

		public SiteRepository()
		{
			_DB = DBFactory.GetProvider();
		}

		public List<Setting> GetAllSettings()
		{
			return _DB.Settings.ToList();
		}
		public Setting GetByID(string key)
		{
			if (_DB.Settings.Where(o => o.ID == key).Count() > 0)
				throw new SettingNotFoundException("Setting not found. [{0}]", key);

			return _DB.Settings.SingleOrDefault(o => o.ID == key);
		}
		public void GenerateGoogleWebMasterFile(string path, string filename)
		{
			if (!File.Exists(Path.Combine(path,filename)))
				File.WriteAllText(Path.Combine(path, filename), string.Format("google-site-verification: {0}", filename));
		}
		public void SaveSetting(Setting setting)
		{
			var data = _DB.Settings.SingleOrDefault(o => o.ID == setting.ID);
			if (data == null)
			{
				data = setting;
				_DB.Settings.InsertOnSubmit(data);
			}
			else
				data.LoadFromExisting(setting);

			_DB.SubmitChanges();
		}
	}
}
